package com.xhh.fs.interceptor;

import com.xhh.fs.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String contextPath = session.getServletContext().getContextPath();//获取项目根路径
        String[] requireAuthPages = new String[]{//存放需要拦截的路径(单页面应用)
                "index",
        };
        String uri = request.getRequestURI();//获取当前请求的具体路径
        uri = StringUtils.remove(uri, contextPath + "/");//去掉前缀
        String page = uri;
        //判断拦截，若没有登录认证则跳转到登录页
        if (beginWith(page, requireAuthPages)){
            User user = (User) session.getAttribute("user");
            if (user == null){
                response.sendRedirect("login");
            }
            return false;
        }
        return true;
    }

    //判断是否需要拦截
    //page:当前访问页面；requireAuthPages：存储需要拦截的页面
    private boolean beginWith(String page, String[] requireAuthPages){
        boolean result = false;
        for (String requireAuthPage : requireAuthPages){
            if (StringUtils.startsWith(page,requireAuthPage)){
                result = true;
                break;
            }
        }
        return result;
    }
}
